package com.tiancheng.trade.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tiancheng.trade.commom.core.data.Result;
import com.tiancheng.trade.commom.core.exception.BusinessException;
import com.tiancheng.trade.commom.core.exception.error.BusinessErrorInfoEnum;
import com.tiancheng.trade.commom.core.utils.JsonUtil;
import com.tiancheng.trade.order.bo.CreditOrderPayQueryBo;
import com.tiancheng.trade.order.bo.CreditOrderQueryDetailBo;
import com.tiancheng.trade.order.bo.OrderBO;
import com.tiancheng.trade.order.bo.SubOrderBO;
import com.tiancheng.trade.order.bo.cmq.CreditOrderBO;
import com.tiancheng.trade.order.bo.cmq.CreditOrderFundAuthFreezeBo;
import com.tiancheng.trade.order.enums.*;
import com.tiancheng.trade.order.feign.CreditSystemService;
import com.tiancheng.trade.order.mapper.CreditOrderMapper;
import com.tiancheng.trade.order.model.CreditOrder;
import com.tiancheng.trade.order.model.CreditOrderOperation;
import com.tiancheng.trade.order.model.CreditOrderPayRecord;
import com.tiancheng.trade.order.service.CreditOrderOperationService;
import com.tiancheng.trade.order.service.CreditOrderPayRecordService;
import com.tiancheng.trade.order.service.CreditOrderService;
import com.tiancheng.trade.order.service.OrderParallelService;
import com.tiancheng.trade.order.util.*;
import com.tiancheng.trade.commom.core.data.MessageBody;
import com.tiancheng.trade.order.mq.MessageProducer;
import com.tiancheng.trade.order.vo.api.CreditOrderCancelVo;
import com.tiancheng.trade.order.vo.api.CreditOrderFinishVO;
import com.tiancheng.trade.order.vo.api.CreditOrderVo;
import com.tiancheng.trade.order.vo.api.SettlementInfoVo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 类 描 述：信用订单操作
 * 创建时间：2024-09-16 13:49
 * 创 建 人：likailun
 */
@Slf4j
@Service
public class CreditOrderServiceImpl implements CreditOrderService {

    @Resource
    private CreditOrderMapper creditOrderMapper;
    @Resource
    private CreditSystemService creditSystemService;
    @Resource
    private CreditOrderOperationService creditOrderOperationService;
    @Resource
    private CreditOrderPayRecordService creditOrderPayRecordService;
    @Resource
    private OrderParallelService orderParallelService;
    @Resource
    private MessageProducer messageProducer;
    @Resource
    private MerchantInfoConfig merchantInfoConfig;

    @Override
    public void create(OrderBO orderBO, List<SubOrderBO> subOrderBOS) throws BusinessException {
        CreditOrder co = queryByOrderId(orderBO.getOrderId());
        if (co != null) {
            return;
        }
        SettlementInfoVo cb = getSettlementInfoVo(orderBO);
        if (cb == null) return;
        log.info("信用授权单判断，SettlementInfo:{}", JsonUtil.toJsonString(cb));
        if (cb.getIsCreditOrder() != null && cb.getIsCreditOrder().equals(1)) {
            BusinessErrorInfoEnum.ORDER_CREDIT_DEPOSIT_AMOUNT_ERROR.assertIsTrue(cb.getDepositAmount()!=null &&
                    cb.getDepositAmount()>0);
            // 主订单Id
            CreditOrder creditOrder = new CreditOrder();
            creditOrder.setOrderId(orderBO.getOrderId());
            creditOrder.setAlipayAuthNo("");// 初始空
            creditOrder.setUid(orderBO.getUid());
            creditOrder.setPlatformOrderId(StringUtils.isEmpty(cb.getPlatformOrderId())?"":cb.getPlatformOrderId());
            creditOrder.setOrderState(CreditOrderStateEnum.CREATED.getCode());
            creditOrder.setTotalAmount(cb.getDepositAmount());
            creditOrder.setTotalFreezeAmount(0);
            creditOrder.setTotalFreezeCreditAmount(0);
            creditOrder.setTotalFreezeFundAmount(0);
            creditOrder.setTotalPayAmount(0);
            creditOrder.setRestAmount(0);
            creditOrder.setAuthStatus(CreditOrderAuthStatusEnum.INIT.getCode());
            creditOrder.setProductName(orderBO.getOrderName());
            creditOrder.setCreditAuthType(CreditOrderCreditAuthTypeEnum.CREDIT.getCode());
            creditOrder.setContractState(CreditOrderContractStateEnum.OBSERVE.getCode());
            creditOrder.setCreatedBy(orderBO.getUid());
            creditOrder.setMerchantId(StringUtils.isEmpty(orderBO.getMerchantCode()) ? subOrderBOS.get(0).getMerchantCode() : orderBO.getMerchantCode());
            creditOrder.setCreatedDt(LocalDateTime.now());
            creditOrder.setDisabled(CreditOrderDisabledEnum.ACTIVE.getCode());
            if (!StringUtils.isEmpty(cb.getCreditType())) {
                String desc = CreditOrderCreditTypeEnum.getDesc(cb.getCreditType());
                BusinessErrorInfoEnum.ORDER_CREDIT_CREDIT_ORDER_NO_EXIST.assertNotNull(desc);
            }
            creditOrder.setCreditType(StringUtils.isEmpty(cb.getCreditType()) ? CreditOrderCreditTypeEnum.ZHIMA.getCode() : cb.getCreditType());
            creditOrderMapper.insert(creditOrder);
        }
    }

    @Override
    public String getOrderStr(String orderId, String compatible) throws BusinessException {
        // 兼容老订单系统请求
        if (isOldOrderByOrderId(orderId) && OrderParallelUtil.needCompatible(compatible)) {
            return orderParallelService.getOrderStr(orderId);
        }
        CreditOrder co = queryByOrderId(orderId);
        BusinessErrorInfoEnum.ORDER_CREDIT_NO_EXIST.assertNotNull(co);
        String gwOrderId = getGwOrderId(co);
        CreditOrderOperation creditOrderOperation = creditOrderOperationService.create(orderId, co.getCreditType(),
                CreditOrderOperationTypeEnum.FREEZE.getCode(), gwOrderId, "发起预授权请求");
        Map<String, Object> params = new HashMap<>();
        params.put("gwOrderId", gwOrderId);
        params.put("userId", co.getUid());
        params.put("productName", co.getProductName());
        params.put("totalAmount", null==co.getTotalAmount()?"":co.getTotalAmount().toString());
        params.put("merchantId", merchantInfoConfig.getCreditSystemMerchantCode(co.getMerchantId()));
        params.put("requestNo", creditOrderOperation.getOutRequestNo());
        return creditSystemService.freeze(params);
    }

    @Override
    public Result finishCreditOrder(CreditOrderFinishVO creditOrderFinishVO) throws BusinessException {
        // 兼容老订单系统请求
        String description = StringUtils.isEmpty(creditOrderFinishVO.getDescription()) ? "业务订单完成" : creditOrderFinishVO.getDescription();
        List<CreditOrder> creditOrders = queryByAlipayAuthNo(creditOrderFinishVO.getAlipayAuthNo());
        if (CollectionUtils.isEmpty(creditOrders)) {
            // 查询老订单系统是否有该订单
            if(OrderParallelUtil.needCompatible(creditOrderFinishVO.getCompatible())){
                CreditOrderVo creditOrderVo = orderParallelService.queryCreditOrder(creditOrderFinishVO.getAlipayAuthNo());
                BusinessErrorInfoEnum.ORDER_CREDIT_NO_EXIST.assertNotNull(creditOrderVo);
                // 调用老订单系统
                return orderParallelService.finishCreditOrder(creditOrderFinishVO.getAlipayAuthNo(), creditOrderFinishVO.getPayAmount(),
                        creditOrderFinishVO.getBizComplete(), description);
            }
        }
        BusinessErrorInfoEnum.ORDER_CREDIT_NO_EXIST.assertIsTrue(!CollectionUtils.isEmpty(creditOrders));
        CreditOrder creditOrder = creditOrders.get(0);
        creditOrder.setTotalPayAmount(creditOrderFinishVO.getPayAmount());
        // 订单累计剩余金额
        creditOrder.setRestAmount(creditOrder.getTotalAmount() - creditOrderFinishVO.getPayAmount());
        creditOrder.setContractState(creditOrderFinishVO.getBizComplete());
        if (creditOrder.getTotalPayAmount() != null && creditOrder.getTotalPayAmount() > 0) {
            //授权转支付
            log.info("完成信用授权订单--->>授权转支付,{}",creditOrderFinishVO.toString());
            pay(creditOrder, creditOrderFinishVO.getDescription());
        } else {
            // 解冻
            log.info("完成信用授权订单--->>解冻授权冻结,{}",creditOrderFinishVO.toString());
            unfreeze(creditOrder, creditOrderFinishVO);
        }
        creditOrder.setDescription(description);
        changeState(creditOrder, CreditOrderStateEnum.FINISHED, creditOrder.getDescription());
        return Result.success();
    }

    @Override
    public Result cancel(CreditOrderCancelVo orderCancel) throws BusinessException {
        // 兼容老订单系统请求
        String remark = StringUtils.isEmpty(orderCancel.getRemark()) ? "预授权订单取消" : orderCancel.getRemark();
        List<CreditOrder> creditOrders = queryByAlipayAuthNo(orderCancel.getAlipayAuthNo());
        if (CollectionUtils.isEmpty(creditOrders)) {
            // 查询老订单系统是否有该订单
            if(OrderParallelUtil.needCompatible(orderCancel.getCompatible())){
                CreditOrderVo creditOrderVo = orderParallelService.queryCreditOrder(orderCancel.getAlipayAuthNo());
                BusinessErrorInfoEnum.ORDER_CREDIT_NO_EXIST.assertNotNull(creditOrderVo);
                // 调用老订单系统-取消预授权订单订单
                return orderParallelService.cancelCreditOrder(orderCancel.getAlipayAuthNo(), remark);
            }
        }

        BusinessErrorInfoEnum.ORDER_CREDIT_NO_EXIST.assertIsTrue(!CollectionUtils.isEmpty(creditOrders));
        CreditOrderOperation creditOrderOperation = creditOrderOperationService.queryByOrderIdAndOperationType(creditOrders.get(0).getOrderId(), CreditOrderOperationTypeEnum.FREEZE.getCode());
        BusinessErrorInfoEnum.ORDER_CREDIT_FREEZE_NO_EXIST.assertNotNull(creditOrderOperation);
        BusinessErrorInfoEnum.ORDER_CREDIT_FREEZE_CANCEL_STATE_ERROR.assertIsTrue(creditOrderOperation.getOperationStatus().equals(CreditOrderOperationStatusEnum.SUCCESS.getCode()));
        Map<String, Object> params = new HashMap<>(4);
        params.put("gwOrderId", getGwOrderId(creditOrders.get(0)));
        params.put("requestNo", creditOrderOperation.getOutRequestNo());
        params.put("remark", remark);
        params.put("merchantId", merchantInfoConfig.getCreditSystemMerchantCode(creditOrders.get(0).getMerchantId()));
        creditSystemService.cancel(params);
        return Result.success();
    }

    @Override
    public CreditOrder updateFundAuthFreeze(CreditOrderFundAuthFreezeBo payNotifyBO) {
        // 信用订单预授权冻结-回调结果处理
        List<CreditOrder> creditOrders = this.creditOrderMapper.selectList(new LambdaQueryWrapper<CreditOrder>()
                .eq(CreditOrder::getGwOrderId, payNotifyBO.getGwOrderId()).eq(CreditOrder::getDisabled, CreditOrderDisabledEnum.ACTIVE.getCode()));
        CreditOrder order = null;
        if (!CollectionUtils.isEmpty(creditOrders)) {
            for (CreditOrder creditOrder : creditOrders) {
                creditOrder.setAlipayAuthNo(payNotifyBO.getAlipayAuthNo());
                creditOrder.setTotalFreezeAmount(payNotifyBO.getTotalFreezeAmount());
                creditOrder.setAlipayPayerLogonId(payNotifyBO.getAlipayPayerLogonId());
                creditOrder.setAlipayPayeeUserId(payNotifyBO.getAlipayPayeeUserId());
                creditOrder.setAlipayPayerUserId(payNotifyBO.getAlipayPayerUserId());
                //资金预授权状态-用户已确认授权
                creditOrder.setAuthStatus(CreditOrderAuthStatusEnum.SUCCESS.getCode());
                creditOrder.setCreditAuthType("CREDIT");
                creditOrder.setPreAuthTime(LocalDateTime.now());
                //如果当前预授权订单状态还是CREATED状态，则更新冻结流水
                if (!creditOrder.getOrderState().equals(CreditOrderStateEnum.CREATED.getCode())) {
                    order=creditOrder;
                    continue;
                }
                // 修改免押订单状态、支付宝单号等信息
                creditOrderOperationService.updateOperation(creditOrder, payNotifyBO, CreditOrderOperationTypeEnum.FREEZE, "用户授权冻结");
                log.info("信用订单预授权冻结成功：{}",payNotifyBO.toString());
                // 修改主表状态：用户已确认授权
                order = changeState(creditOrder, CreditOrderStateEnum.USER_ACCEPTED, "用户授权冻结");
            }
        }
        return order;
    }

    @Override
    public CreditOrder tradeStatusSync(String gwOrderId) {
        List<CreditOrder> creditOrders = this.creditOrderMapper.selectList(new LambdaQueryWrapper<CreditOrder>()
                .eq(CreditOrder::getGwOrderId, gwOrderId));
        if (!CollectionUtils.isEmpty(creditOrders)) {
            CreditOrderPayQueryBo creditOrderPayQueryBo = sendQueryPayRequest(creditOrders.get(0));
            // 修改预转支付记录结果
            if(null!=creditOrderPayQueryBo){
                return updatePaidStatus(creditOrderPayQueryBo, creditOrders.get(0));
            }
        }
        return null;
    }

    @Override
    public CreditOrder cancelConfirm(String gwOrderId, String requestNo) {
        //信用订单预授权操作取消-回调结果
        List<CreditOrder> creditOrders = this.creditOrderMapper.selectList(new LambdaQueryWrapper<CreditOrder>()
                .eq(CreditOrder::getGwOrderId, gwOrderId));
        if (!CollectionUtils.isEmpty(creditOrders)) {
            log.info("信用订单取消成功成功，orderId:{}，requestNo：{}",creditOrders.get(0).getOrderId(),requestNo);
            // 修改预授权订单状态：用户取消
            return changeState(creditOrders.get(0), CreditOrderStateEnum.REVOKED, "预授权订单取消成功");
        }
        return null;
    }

    @Override
    public CreditOrder fundAuthUnfreeze(String gwOrderId, String requestNo) {
        // 信用订单预授权解冻-结果结果
        List<CreditOrder> creditOrders = this.creditOrderMapper.selectList(new LambdaQueryWrapper<CreditOrder>()
                .eq(CreditOrder::getGwOrderId, gwOrderId));
        if (!CollectionUtils.isEmpty(creditOrders)) {
            CreditOrder creditOrder = creditOrders.get(0);
            CreditOrderFundAuthFreezeBo cf = new CreditOrderFundAuthFreezeBo();
            cf.setRequestNo(requestNo);
            cf.setGwOrderId(gwOrderId);
            String remark = "预授权订单解冻成功";
            // 修改流水操作记录状态
            creditOrderOperationService.updateOperation(creditOrder, cf, CreditOrderOperationTypeEnum.UNFREEZE, remark);
            // 修改预转支付记录结果
            return changeState(creditOrder, CreditOrderStateEnum.USER_PAID, remark);
        }
        return null;
    }

    @Override
    public Result<CreditOrderVo> queryCreditOrderByAlipayAuthNo(String alipayAuthNo, String compatible) throws BusinessException{
        List<CreditOrder> creditOrders = queryByAlipayAuthNo(alipayAuthNo);
        if (!CollectionUtils.isEmpty(creditOrders)) {
            Optional<CreditOrderVo> convert = ObjectConvertUtil.convert(creditOrders.get(0), CreditOrderVo.class);
            return Result.success(convert.get());
        }
        CreditOrderVo creditOrderVo = null;
        if(OrderParallelUtil.needCompatible(compatible)){
            // 查询老订单系统是否存在该笔信用订单
            creditOrderVo=orderParallelService.queryCreditOrder(alipayAuthNo);
        }
        BusinessErrorInfoEnum.ORDER_CREDIT_NO_EXIST.assertNotNull(creditOrderVo);
        return Result.success(creditOrderVo);
    }

    @Override
    public CreditOrderVo queryConfirmStatusByOrderId(String orderId, String compatible) throws BusinessException {

        if(isOldOrderByOrderId(orderId) && OrderParallelUtil.needCompatible(compatible)){
            return orderParallelService.queryConfirmStatus(orderId);
        }
        CreditOrder creditOrder = this.queryByOrderId(orderId);
        BusinessErrorInfoEnum.ORDER_CREDIT_NO_EXIST.assertNotNull(creditOrder);
        CreditOrderOperation co = creditOrderOperationService.queryByOrderIdAndOperationType(orderId, CreditOrderOperationTypeEnum.FREEZE.getCode());
        BusinessErrorInfoEnum.ORDER_CREDIT_NO_EXIST.assertNotNull(co);
        // 再次查询
        CreditOrderQueryDetailBo cob = creditSystemService.detailQuery(co.getOutRequestNo(), creditOrder.getGwOrderId(), creditOrder.getMerchantId());
        if(null!=cob){
            if(cob.getStatus().equals("SUCCESS")){
                CreditOrderFundAuthFreezeBo fb = new CreditOrderFundAuthFreezeBo();
                fb.setGwOrderId(cob.getGwOrderId());
                fb.setRequestNo(co.getOutRequestNo());
                fb.setAlipayAuthNo(cob.getAlipayAuthNo());
                fb.setTotalFreezeAmount(CommonUtil.long2Integer(cob.getTotalFreezeAmount()));
                fb.setAlipayPayerLogonId(creditOrder.getAlipayPayerLogonId());
                fb.setAlipayPayeeUserId(creditOrder.getAlipayPayeeUserId());
                CreditOrder newCreditOrder = this.updateFundAuthFreeze(fb);
                Optional<CreditOrderVo> convert = ObjectConvertUtil.convert(newCreditOrder, CreditOrderVo.class);

                // 发送到业务侧
                messageProducer.tallyBizCreditOrder(creditOrder2CreditOrderBO(newCreditOrder), CreditOrderMsgTagEnum.FUND_AUTH_FREEZE);
                return convert.orElse(null);
            }
        }
        return null;
    }

    @Override
    public Result updateCreditOrderState(MessageBody messageBody) {
        Map<String, Object> param = new HashMap<>();
        param.put("message_type",messageBody.getMessageType());
        param.put("message_data",messageBody.getData());
        Result result = orderParallelService.updateCreditOrderState(param);
        if(result.getRet()==0){
            Map map = JsonUtil.fromJson(JsonUtil.toJsonString(messageBody.getData()), Map.class);
            CreditOrderVo alipayAuthNo = orderParallelService.queryCreditOrder(map.get("alipayAuthNo").toString());
            result.setData(alipayAuthNo);
        }
        return result;
    }

    /**
     * 请求预授权订单授权转支付
     */
    private void pay(CreditOrder co, String description) {
        String gwOrderId = getGwOrderId(co);
        CreditOrderOperation creditOrderOperation = creditOrderOperationService.create(co.getOrderId(), co.getCreditType(), CreditOrderOperationTypeEnum.PAY.getCode(), gwOrderId, "授权转支付");
        CreditOrderPayRecord orderPayRecord = creditOrderPayRecordService.get(gwOrderId);
        if(orderPayRecord!=null){
            CreditOrderPayQueryBo creditOrderPayQueryBo = sendQueryPayRequest(co);
            if (creditOrderPayQueryBo != null) {
                if (!StringUtils.isEmpty(creditOrderPayQueryBo.getTradeStatus()) && creditOrderPayQueryBo.getTradeStatus().equals(CreditOrderTradeStatusEnum.TRADE_SUCCESS.getCode())) {
                    updatePaidStatus(creditOrderPayQueryBo, co);
                    return;
                }
            }
        }
        // 调用支付宝支付
        Map<String, Object> payParams = new HashMap<>(10);
        payParams.put("gwOrderId", gwOrderId);
        payParams.put("alipayAuthNo", co.getAlipayAuthNo());
        payParams.put("alipayBuyerId", co.getAlipayPayerUserId());
        payParams.put("alipaySellerId", co.getAlipayPayeeUserId());
        payParams.put("subject", StringUtils.isEmpty(description) ? "还车抵扣" : description);
        payParams.put("totalAmount", co.getTotalPayAmount());
        payParams.put("merchantId", merchantInfoConfig.getCreditSystemMerchantCode(co.getMerchantId()));
        payParams.put("authConfirmMode", "COMPLETE");
        payParams.put("requestNo", creditOrderOperation.getOutRequestNo());
        payParams.put("remark", "授权转支付");
        creditSystemService.tradePay(payParams);
    }

    /**
     * 查询预授转支付信息
     *
     * @param co
     * @return
     */
    private CreditOrderPayQueryBo sendQueryPayRequest(CreditOrder co) {
        Map<String, Object> params = new HashMap<>(2);
        params.put("gwOrderId", getGwOrderId(co));
        params.put("merchantId", merchantInfoConfig.getCreditSystemMerchantCode(co.getMerchantId()));
        return creditSystemService.tradePayQuery(params);
    }


    /**
     * 请求解冻预授权订单
     */
    private void unfreeze(CreditOrder co, CreditOrderFinishVO creditOrderFinishVO) {
        CreditOrderOperation creditOrderOperation = creditOrderOperationService.create(co.getOrderId(), co.getCreditType(), CreditOrderOperationTypeEnum.UNFREEZE.getCode(), getGwOrderId(co), "解冻预授权订单");
        HashMap<String, Object> params = new HashMap<>(6);
        params.put("alipayAuthNo", co.getAlipayAuthNo());
        params.put("amount", co.getTotalFreezeAmount());
        params.put("remark", "解冻预授权订单");
        params.put("bizComplete", creditOrderFinishVO.getBizComplete());
        params.put("merchantId", merchantInfoConfig.getCreditSystemMerchantCode(co.getMerchantId()));
        params.put("requestNo", creditOrderOperation.getOutRequestNo());
        Result unfreeze = creditSystemService.unfreeze(params);
        BusinessErrorInfoEnum.ORDER_CREDIT_UNFREEZE_ERROR.assertIsTrue(unfreeze!=null && unfreeze.getRet()==0);
    }

    /**
     * 根据查询到的支付结果来更新订单支付信息
     *
     * @param creditOrderPayQueryBo
     */
    private CreditOrder updatePaidStatus(CreditOrderPayQueryBo creditOrderPayQueryBo, CreditOrder co) {
        // 添加支付记录
        creditOrderPayRecordService.create(creditOrderPayQueryBo, co.getOrderId(), co.getCreditType());
        //修改支付状态
        co.setTotalPayAmount(CommonUtil.long2Integer(creditOrderPayQueryBo.getBuyerPayAmount()));
        CreditOrder creditOrder = changeState(co, CreditOrderStateEnum.USER_PAID, "预授权转支付成功");
        //  更新流水表支付状态
        creditOrderOperationService.updatePaidOperation(co.getOrderId(), co.getAlipayAuthNo(), co.getTotalPayAmount());
        log.info("信用订单预授权转支付成功，orderId：{},回调数据：{}",co.getOrderId(),creditOrderPayQueryBo.toString());
        return creditOrder;
    }

    /**
     * 更新信用订单表orderState
     */
    private CreditOrder changeState(CreditOrder co, CreditOrderStateEnum stateEnum, String desc) {
        co.setOrderState(stateEnum.getCode());
        co.setDescription(desc);
        co.setLastUpdDt(LocalDateTime.now());
        this.creditOrderMapper.update(co, new LambdaQueryWrapper<CreditOrder>().eq(CreditOrder::getId, co.getId()));
        return co;
    }

    private String getGwOrderId(CreditOrder co) {
        String gwOrderId = co.getGwOrderId();
        if (StringUtils.isEmpty(gwOrderId)) {
            gwOrderId = getGwOrderIdByOrderId(co.getOrderId());
            co.setGwOrderId(gwOrderId);
            // 过期时间15天
            co.setGwOrderIdExpiryTime(LocalDateTime.now().plusDays(15));
            creditOrderMapper.update(co, new LambdaQueryWrapper<CreditOrder>().eq(CreditOrder::getId, co.getId()));
        } else if (co.getOrderState().equals(CreditOrderStateEnum.CREATED.getCode()) && LocalDateTime.now().isAfter(co.getGwOrderIdExpiryTime())) {
            // 超过15天，重新生成订单号和过期时间
            String suffix = gwOrderId.substring(gwOrderId.length() - 2);
            gwOrderId = co.getOrderId() + (Integer.parseInt(suffix) + 1);
            co.setGwOrderId(gwOrderId);
            // 过期时间15天
            co.setGwOrderIdExpiryTime(LocalDateTime.now().plusDays(15));
            creditOrderMapper.update(co, new LambdaQueryWrapper<CreditOrder>().eq(CreditOrder::getId, co.getId()));
        }
        return gwOrderId;
    }

    private CreditOrder queryByOrderId(String orderId) {
        if (StringUtils.isEmpty(orderId)) {
            return null;
        }
        List<CreditOrder> creditOrders = creditOrderMapper.selectList(new LambdaQueryWrapper<CreditOrder>()
                .eq(CreditOrder::getOrderId, orderId).eq(CreditOrder::getDisabled, CreditOrderDisabledEnum.ACTIVE.getCode()));
        return CollectionUtils.isEmpty(creditOrders) ? null : creditOrders.get(0);
    }


    /**
     * SettlementInfo 参数解析
     * @param orderBO
     * @return
     */
    private SettlementInfoVo getSettlementInfoVo(OrderBO orderBO) {
        SettlementInfoVo cb = null;
        try {

            JSONArray objects = JSON.parseArray(orderBO.getSettlementInfo());
            if (objects==null || objects.size()==0) {
                return null;
            }
            cb = JSON.parseObject(objects.get(0).toString(), SettlementInfoVo.class);
            if (cb.getIsCreditOrder() == null || cb.getIsCreditOrder().equals(0)) {
                return null;
            }

        } catch (Exception e) {
            log.info("SettlementInfo转换CreditOrderBo异常", e);
        }
        return cb;
    }

    /**
     * 是否老订单
     *
     * @param orderId 订单号
     * @return
     */
    private boolean isOldOrderByOrderId(String orderId) {
        return OrderParallelUtil.isOrderSubSystem(orderId);
    }

    /**
     * 根据alipayAuthNo 查询订单
     *
     * @param alipayAuthNo 支付宝授权单号
     * @return
     */
    private List<CreditOrder> queryByAlipayAuthNo(String alipayAuthNo) {
        List<CreditOrder> creditOrders = this.creditOrderMapper.selectList(new LambdaQueryWrapper<CreditOrder>()
                .eq(CreditOrder::getAlipayAuthNo, alipayAuthNo).eq(CreditOrder::getDisabled, CreditOrderDisabledEnum.ACTIVE.getCode()));

        return creditOrders;
    }

    /**
     * 获取业务侧订单号
     *
     * @param orderBO
     * @return
     */
    private String getPlatformOrderId(OrderBO orderBO) {
        if (!StringUtils.isEmpty(orderBO.getTradeInfo())) {
            try {
                JSONObject jsonObject = JSON.parseObject(orderBO.getTradeInfo());
                if (jsonObject.containsKey("platform_order_id")) {
                    return jsonObject.getString("platform_order_id");
                }
                return "";
            } catch (Exception ignored) {
            }
        }
        return "";
    }

    private CreditOrderBO creditOrder2CreditOrderBO(CreditOrder creditOrder){
        Optional<CreditOrderBO> convert = ObjectConvertUtil.convert(creditOrder, CreditOrderBO.class);
        return convert.orElse(null);
    }

    /**
     * 生成信用订单号（ 芝麻商户授权资金订单号）
     * 规则：在主订单号的末位加两位，默认从10开始，客户端下押金订单时，如果已经到了过期时间，则更新该订单号，在此基础上累加：11、12、13...
     *
     * @param orderId
     * @return
     */
    private String getGwOrderIdByOrderId(String orderId) {
        return orderId + "10";
    }
}
